import React, { MouseEventHandler, useEffect, useState } from "react"
import { Component, useComponentsStore } from "../../editor/stores/components"
import { useComponentConfigStore } from "../../editor/stores/component-config"
import HoverMask from "../HoverMask"
import SelectMark from "../../editor/components/SelectMark"

const EditArea = () => {
  const { components, curComponentId, setCurComponentId } = useComponentsStore()
  const { componentConfig } = useComponentConfigStore()

  useEffect(() => {}, [])

  function renderComponents(components: Component[]): React.ReactNode {
    return components.map((component: Component) => {
      const config = componentConfig?.[component.name]

      if (!config?.component) {
        return null
      }

      return React.createElement(
        config.component,
        {
          key: component.id,
          id: component.id,
          name: component.name,
          styles: component.styles,
          ...config.defaultProps,
          ...component.props,
        },
        renderComponents(component.children || [])
      )
    })
  }

  const handleClick: MouseEventHandler = (e) => {
    const path = e.nativeEvent.composedPath()

    for (let i = 0; i < path.length; i += 1) {
      const ele = path[i] as HTMLElement

      const componentId = ele.dataset?.componentId
      if (componentId) {
        setCurComponentId(+componentId)
        return
      }
    }
  }

  const [hoverComponentId, setHoverComponentId] = useState<number>()

  const handleMouseOver: MouseEventHandler = (e) => {
    const path = e.nativeEvent.composedPath()
    for (let i = 0; i < path.length; i += 1) {
      const element = path[i] as HTMLElement

      const componentId = element.dataset?.componentId
      if (componentId) {
        setHoverComponentId(+componentId)
        return
      }
    }
  }

  return (
    <div
      className="w-full h-full edit-area"
      onMouseOver={handleMouseOver}
      onMouseLeave={() => setHoverComponentId(undefined)}
      onClick={handleClick}
    >
      {renderComponents(components)}
      {hoverComponentId && hoverComponentId !== curComponentId && (
        <HoverMask
          portalWrapperClassName="portal-wrapper"
          containerClassName="edit-area"
          componentId={hoverComponentId}
        />
      )}
      {curComponentId && (
        <SelectMark
          portalWrapperClassName="portal-wrapper"
          containerClassName="edit-area"
          componentId={curComponentId}
        />
      )}
      <div className="portal-wrapper"></div>
    </div>
  )
}

export default EditArea
